# 日活跃用户统计
# tb users表的last loqin宇段的日期等于今天的数量

from apps.users.models import User
from datetime import date

# 属性名称和比较运算符问使用两个下划线，所以属性名不能包括多个下划线
# 属性名称__比较运算符=值
# 我们这里用不到序列化器，所以中APIView就行
from rest_framework.views import APIView
from rest_framework.response import Response
from datetime import timedelta


class DailyActiveAPIView(APIView):
    """日活跃用户"""

    def get(self, request):
        today = date.today()  # 自动转换成年月日零时零分零秒
        count = User.objects.filter(last_login__gte=today).count()  # 登录时间大于今天零时零分零秒的用户个数
        return Response({'count': count, 'date': today})


class OrderCountAPIView(APIView):
    """日下单用户量"""

    def get(self, request):
        today = date.today()
        """
        关联过滤查询
        由多方模型类条件查询一方模型类数据，
        语法如下:
        关联模型类名小写__属性名__条件运算符=值
        注意:如果没有"运算符"部分， 表示等于。
        """
        # 订单创建时间大于今天的用户，关联过滤查询，用户--》订单 一对多
        count = User.objects.filter(orderinfo__create_time__gte=today).count()
        return Response({"count": count, "date": today})


class MonthCountAPIView(APIView):
    """月新增用户"""

    def get(self, request):
        today = date.today()
        begin_date = today - timedelta(days=30)  # 从今天开始往前30天的日期

        data_list = []
        for i in range(1, 31):
            start_date = begin_date + timedelta(days=i)  # 今天开始的前30那天的时间
            end_date = begin_date + timedelta(days=i + 1)  # 第二天的零时零分零秒
            # 获取每一天新增的用户，时间在当天零时零分零秒到第二天零时零分零秒之间的用户
            count = User.objects.filter(date_joined__gte=start_date, date_joined__lt=end_date).count()

            data_list.append({
                "count": count,
                "date": start_date
            })

        return Response(data_list)


class UserCountAPIView(APIView):
    """用户总量统计"""

    def get(self, request):
        today = date.today()
        tomorrow = today + timedelta(days=1)
        count = User.objects.filter(date_joined__lt=tomorrow).count()

        return Response({"count": count, "date": today})


class UserDayCountAPIView(APIView):
    """日增用户统计"""

    def get(self, request):
        today = date.today()
        tomorrow = today + timedelta(days=1)
        count = User.objects.filter(date_joined__gte=today, date_joined__lt=tomorrow).count()

        return Response({"count": count, "date": today})
